package com.bocloud.cmp.driver.providers.jd;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bocloud.cmp.driver.providers.VolumeDriver;
import com.bocloud.cmp.enums.VolumeCategory;
import com.bocloud.cmp.model.SnapshotModel;
import com.bocloud.cmp.model.VolumeModel;
import com.bocloud.common.model.BsmResult;
import com.google.common.collect.Lists;
import com.jcloud.cap.client.ClientConfig;
import com.jcloud.cap.client.IClient;
import com.jcloud.cap.client.JCloudClient;
import com.jcloud.cap.client.builder.v1.CreateVolumeRequestBuilder;
import com.jcloud.cap.client.builder.v1.DeleteVolumeRequestBuilder;
import com.jcloud.cap.client.builder.v1.PayRequestBuilder;
import com.jcloud.cap.client.builder.v1.QueryVolumeDetailRequestBuilder;
import com.jcloud.cap.client.builder.v1.QueryVolumesRequestBuilder;
import com.jcloud.cap.client.exception.ClientException;
import com.jcloud.cap.client.exception.ServerException;
import com.jcloud.cap.client.http.HttpConfig;
import com.jcloud.cap.data.model.v1.CreateVolumeResponse;
import com.jcloud.cap.data.model.v1.DeleteVolumeResponse;
import com.jcloud.cap.data.model.v1.PayRequest;
import com.jcloud.cap.data.model.v1.QueryVolumeDetailResponse;
import com.jcloud.cap.data.model.v1.QueryVolumesResponse;
import com.jcloud.cap.data.model.v1.VolumeResponse.Volume;

public class JdVolumeDriver extends JdDriver implements VolumeDriver {
	private static Logger logger = LoggerFactory.getLogger(JdVolumeDriver.class);
	private IClient client;

	/**
	 * @param accessKey
	 * @param secretKey
	 * @param endpoint
	 */
	public JdVolumeDriver(String accessKey, String secretKey, String endpoint, String region) {
		super(accessKey, secretKey, endpoint, region);
		ClientConfig config = new ClientConfig();
		HttpConfig httpConfig = new HttpConfig();
		// 调用地址
		httpConfig.setEndpoint(endpoint);
		httpConfig.setReadTimeout(20000);
		httpConfig.setConnectTimeout(20000);
		config.setHttpConfig(httpConfig);
		config.setCredential(this.getCredential().getCapCredential());
		client = new JCloudClient(config);
	}

	@Override
	public BsmResult list() {
		QueryVolumesRequestBuilder builder = QueryVolumesRequestBuilder.create();
		this.init(builder, "storage", "queryVolumes", this.getRegion());
		try {
			QueryVolumesResponse response = client.send(builder.build());
			List<VolumeModel> models = Lists.newArrayList();
			List<Volume> volumes = response.getVolumes();
			if (null != volumes) {
				for (Volume volume : volumes) {
					String type = null;
					if (volume.getVolumeType().equals("nbd")) {
						type = VolumeCategory.SSD.name();
					} else {
						type = VolumeCategory.EFFICIENCY.name();
					}
					VolumeModel model = new VolumeModel(volume.getVolumeId(), volume.getVolumeName(), type,
							volume.getDescription(), volume.getStatus(), volume.getCreateTime(), volume.getCapacity(),
							null);
					models.add(model);
				}
			}
			return new BsmResult(true, models, "success");
		} catch (ClientException | ServerException e) {
			logger.error("List volume [{}] exception!", e);
			return new BsmResult(false, "List volume failed");
		}
	}

	@Override
	public BsmResult create(VolumeModel volume) {
		CreateVolumeRequestBuilder builder = CreateVolumeRequestBuilder.create();
		this.init(builder, "storage", "createVolume", this.getRegion());
		try {
			String type = null;
			if (volume.getCategory().equals(VolumeCategory.SSD.name())) {
				type = "nbd";
			} else {
				type = "nbd_sata";
			}
			CreateVolumeResponse response = client.send(builder.volumeName(volume.getName()).volumeType(type)
					.capacity(volume.getSize()).description(volume.getRemark()).feeType(1).build());
			PayRequestBuilder payRequestBuilder = PayRequestBuilder.create();
			init(payRequestBuilder, "billing", "pay", this.getRegion());
			PayRequest payRequest = payRequestBuilder.build();
			payRequest.setOrderRequestId(response.getRequestId());
			payRequest.setCoupons(null);
			client.send(payRequest);
			Thread.sleep(1000);
			return detail(volume.getName(), response.getRequestId());
		} catch (ClientException | ServerException | InterruptedException e) {
			logger.error("Create volume [{}] exception!", e);
			return new BsmResult(false, "Create volume failed");
		}

	}

	@Override
	public BsmResult remove(String volumeId) {
		DeleteVolumeRequestBuilder builder = DeleteVolumeRequestBuilder.create();
		this.init(builder, "storage", "deleteVolume", this.getRegion());
		try {
			DeleteVolumeResponse response = client.send(builder.volumeId(volumeId).build());
			return new BsmResult(true, response.getRequestId(), "success");
		} catch (ClientException | ServerException e) {
			logger.error("Reomve volume [{}] exception!", e);
			return new BsmResult(false, "Reomve volume failed");
		}
	}

	@Override
	public BsmResult detail(String volumeId) {
		QueryVolumeDetailRequestBuilder builder = QueryVolumeDetailRequestBuilder.create();
		this.init(builder, "storage", "queryVolumeDetail", this.getRegion());
		try {
			QueryVolumeDetailResponse response = client.send(builder.volumeId(volumeId).build());
			Volume volume = response.getVolume();
			if (null == volume) {
				return new BsmResult(false, "该对象不存在");
			}
			VolumeModel model = new VolumeModel(volume.getVolumeId(), volume.getVolumeName(), volume.getVolumeType(),
					volume.getDescription(), volume.getStatus(), volume.getCreateTime(), volume.getCapacity(), null);
			return new BsmResult(true, model, "success");
		} catch (ClientException | ServerException e) {
			logger.error("Query volume [{}] exception!", e);
			return new BsmResult(false, "Query volume failed");
		}
	}

	private BsmResult detail(String name, String requestId) {
		QueryVolumesRequestBuilder builder = QueryVolumesRequestBuilder.create();
		this.init(builder, "storage", "queryVolumes", this.getRegion());
		try {
			QueryVolumesResponse response = client.send(builder.build());
			VolumeModel model = null;
			List<Volume> volumes = response.getVolumes();
			if (null != volumes) {
				for (Volume volume : volumes) {
					if (volume.getVolumeName().equals(name)) {
						model = new VolumeModel(volume.getVolumeId(), volume.getVolumeName(), volume.getVolumeType(),
								volume.getDescription(), volume.getStatus(), volume.getCreateTime(),
								volume.getCapacity(), null);
						break;
					}
				}
			}
			if (null == model) {
				return new BsmResult(false, "该对象不存在");
			}
			return new BsmResult(true, model, "success");
		} catch (ClientException | ServerException e) {
			logger.error("Query volume [{}] exception!", e);
			return new BsmResult(false, "Query volume failed");
		}
	}

	@Override
	public BsmResult modify(VolumeModel volume) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BsmResult snapshot(SnapshotModel snapshotModel) {
		// TODO Auto-generated method stub
		return null;
	}
}
